﻿using _2008A.PH5._0221_0317.FuXi.IRespository;
using _2008A.PH5._0221_0317.FuXi.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace _2008A.PH5._0221_0317.FuXi.Service
{
    public class BaseService<T> : IBaseService<T> where T : class, new()
    {
        IBaseRespository<T> _respository;

        IUnitOfWork _unitOfWork;

        public BaseService(IBaseRespository<T> respository, IUnitOfWork unitOfWork)
        {
            _respository = respository;
            _unitOfWork = unitOfWork;
        }

        public int Insert(T t)
        {
            //开启事务
            using (var tran = _unitOfWork.GetDbContext().Database.BeginTransaction())
            {
                try
                {
                    _respository.Delete(new List<T>());
                    _respository.Insert(t);
                    //....可以做很多的操作

                    //执行没有错误，则提交事务
                    tran.Commit();
                    var result = _unitOfWork.SaveChanges();
                    return result;
                }
                catch (Exception)
                {
                    //执行sql的操作出现错误，那么就回滚
                    tran.Rollback();
                    return -1;
                }
            }
        }

        public IQueryable<T> Query()
        {
            var list = _respository.Query();
            return list;
        }

        public IQueryable<T> Query(int pageIndex, int pageSize, out int total)
        {
            var list = _respository.Query();
            list = list.Skip((pageIndex-1) * pageSize).Take(pageSize);
            total = list.Count();
            return list;
        }

        public IQueryable<T> Query(Expression<Func<T,bool>> where)
        {
            var list = _respository.Query().Where(where);
            return list;
        }

        public IQueryable<T> Query(Expression<Func<T, bool>> where, int pageIndex, int pageSize, out int total)
        {
            throw new NotImplementedException();
        }

        public IQueryable<T> Query<TKey>(Expression<Func<T, bool>> where, Expression<Func<T, TKey>> sort, bool isAsc, int pageIndex, int pageSize, out int total)
        {
            throw new NotImplementedException();
        }
    }
}
